<template>
  <div class="app-container">

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px" v-show="showSearch">
      <el-form-item label="品牌名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入品牌名称"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="querySearch">搜索</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled = "single"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled = "multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>


      <!-- 功能按钮栏 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table :data="brandList" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="品牌名称" prop="name" width="200"/>
      <el-table-column label="品牌图标" prop="logo" #default="scope">
        <img :src="scope.row.logo" width="50"/>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <!-- 插槽：scope.row 表示插槽中的一行数据 -->
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />


    <!-- 新增或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="brandRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称"/>
        </el-form-item>
        <el-form-item label="品牌图标" prop="logo">
          <el-upload
              class="avatar-uploader"
              :action="imgUpload.url"
              :headers="imgUpload.headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Brand">
//--------------------导入区域 --------------------------------
import {listBrand,addBrand,getBrand,updateBrand,deleteBrand} from '@/api/product/brand'
import {getToken} from "@/utils/auth.js";
import { ElMessage,ElMessageBox } from 'element-plus'

//--------------------声明变量区域 ---------------------------------
const { proxy } = getCurrentInstance();


//定义分页列表数据模型
const brandList = ref([])
//定义列表总记录数模型
const total = ref(2)

const data = reactive({
  queryParams: {
    name: '',
    pageNum: 1,
    pageSize: 2
  },
  form: {
    id: null,
    name: null,
    logo: null,
  },
  imgUpload: {
    url: import.meta.env.VITE_APP_BASE_API + '/file/upload',
    headers: {
      Authorization: 'Bearer ' + getToken()
    }
  },
  rules: {
    name: [{ required: true, message: "品牌名称不能为空", trigger: "blur" }],
    logo: [{ required: true, message: "品牌LOGO不能为空", trigger: "blur" }],
  }
})

const {queryParams, form, imgUpload,rules} = toRefs(data) // 将reactive声明的多个复杂类型变量，转换为单个的ref()响应类型的变量

const loading = ref(false)

const open = ref(false) //控制添加修改dialog弹框是否显示

const title = ref('') //dialog弹框标题


//定义批量操作id列表模型
const ids = ref([]);
//定义单选控制模型
const single = ref(true);
//定义多选控制模型
const multiple = ref(true);

//定义隐藏搜索控制模型
const showSearch = ref(true);



//--------------------声明函数区域 ---------------------------------

function getList() {
  loading.value = true
  listBrand(queryParams.value).then((result) => {  // 为什么是一个result对象；而不是response对象。
    brandList.value = result.rows
    total.value = result.total
    loading.value = false
  })
}

//搜索按钮事件处理
function querySearch() {
  getList()
}

function reset() {
  //debugger
  proxy.resetForm("queryRef");

  //queryParams.value.name = ''
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10

  querySearch()
}

getList() //一来页面就调用getList()，获取表格数据进行回显

//--------------------------------------
function handleAvatarSuccess(result, uploadFile) {
  console.log(result)
  console.log(uploadFile)
  form.value.logo = result.data.url
  proxy.$refs['brandRef'].clearValidate('logo')
}

function resetForm2(){
/*  form.value.id = null
  form.value.name = null
  form.value.logo = null*/

  // form.value = {
  //   id: null,
  //   name: null,
  //   logo: null
  // }
  //debugger
  proxy.resetForm("brandRef");
}

//弹出添加对话框
function handleAdd() {
  open.value = true
  title.value = '新增'
  resetForm2();
}

/*function submit(){
  addBrand(form.value).then(result=>{
    open.value = false
    ElMessage.success(result.msg)
    getList()
  })
}*/


function cancel(){
  open.value = false
  //resetForm2()
}


function handleUpdate(row){
  resetForm2();
  title.value = '修改'
  open.value = true
  var _id = row.id || ids.value
  getBrand(_id).then(result=>{
    form.value = result.data
  })
}

//添加和修改共用一个对话框表单
function submit(){

  proxy.$refs['brandRef'].validate((valid)=>{
    if(valid){ //表单校验成功
      //如何区分是添加操作还是修改操作。
      if(!form.value.id){ //id值不存在，为null,''都是false  ;  进行添加操作
        addBrand(form.value).then(result=>{
          open.value = false
          //ElMessage.success(result.msg)
          proxy.$modal.msgSuccess(result.msg)
          getList()
        })
      }else{ // id值存在进行修改
        updateBrand(form.value).then(result=>{
          open.value = false
          //ElMessage.success(result.msg)
          proxy.$modal.msgSuccess(result.msg)
          getList()
        })
      }
    }else{ //表单校验失败
      proxy.$modal.msgError('表单输入参数有误')
    }
  })



}


/*function handleDelete(row){
  let _id = row.id || ids.value
  ElMessageBox.confirm('您确定要删除这个数据吗?','提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  }).then(()=>{ //确定按钮事件处理
    deleteBrand(_id).then(result=>{
      ElMessage.success(result.msg)
      getList()
    })
  }).catch(()=>{ //取消按钮事件处理
    ElMessage.info('取消删除')
  })
}*/
//优化
function handleDelete(row){
  let _id = row.id || ids.value
  proxy.$modal.confirm('您确定要删除这个数据吗?').then(()=>{ //确定按钮事件处理
    deleteBrand(_id).then(result=>{
      proxy.$modal.msgSuccess(result.msg)
      getList()
    })
  }).catch(()=>{ //取消按钮事件处理
    proxy.$modal.msg('取消删除')
  })
}


function handleSelectionChange(selection) {
  ids.value = selection.map((item)=>{
    return item.id
  })
  single.value = ids.value.length!=1
  multiple.value = ids.value.length == 0
}




</script>





<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>